#include "MainWindow.h"
#include "ui_MainWindow.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QGraphicsRectItem>
#include <QProgressDialog>
#include <QUrl>
#include <QDesktopServices>

#include <QDebug>

#include "core/Global.h"
#include "core/ImgCutter.h"
#include "ui/SampleFrame.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    terminated_task = imgCutter->getTerminatedTask();
    if(terminated_task.isEmpty()){
        ui->actionTerminatedTask->setDisabled(true);
    }

    progress_dialog = new QProgressDialog(this);
    progress_dialog->setWindowTitle(tr("Sliding pictures..."));
    connect(progress_dialog, SIGNAL(canceled()), imgCutter, SLOT(terminate()));

    connect(ui->actionStart, SIGNAL(triggered()), this, SLOT(startProcess()));
    connect(ui->actionPause, SIGNAL(triggered()), imgCutter, SLOT(pause()));
    connect(ui->actionStop, SIGNAL(triggered()), imgCutter, SLOT(terminate()));
    connect(ui->actionClearRects, SIGNAL(triggered()), ui->graphicsView, SLOT(clearRects()));
    connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->actionDisplayToolBar, SIGNAL(triggered(bool)), ui->mainToolBar, SLOT(setShown(bool)));

    connect(ui->InputButton, SIGNAL(clicked()), this, SLOT(on_actionOpen_triggered()));
    connect(ui->OutputButton, SIGNAL(clicked()), this, SLOT(on_actionOutputTo_triggered()));

    connect(ui->menuDisplayLanguage, SIGNAL(triggered(QAction*)), this, SLOT(setDisplayLanguage(QAction*)));
    connect(ui->menuToolBarStyle, SIGNAL(triggered(QAction*)), this, SLOT(setToolButtonStyle(QAction*)));

    connect(imgCutter, SIGNAL(error(QString)), this, SLOT(alertError(QString)));
    connect(imgCutter, SIGNAL(progressRange(int,int)), progress_dialog, SLOT(setRange(int,int)));
    connect(imgCutter, SIGNAL(progressChanged(int)), progress_dialog, SLOT(setValue(int)));
    connect(imgCutter, SIGNAL(saveRectMap(QString)), ui->graphicsView, SLOT(saveRectMap(QString)));

    connect(ui->graphicsView, SIGNAL(blankAreaDblClicked()), this, SLOT(on_actionOpen_triggered()));

    if(Config.contains("window/Position")){
        move(Config.value("window/Position").toPoint());
    }
    if(Config.contains("window/Size")){
        resize(Config.value("window/Size").toSize());
    }
    if(Config.contains("window/State")){
        setWindowState((Qt::WindowStates) Config.value("window/State").toInt());
    }
    if(Config.contains("window/hideToolBar") && Config.value("window/hideToolBar").toBool()){
        ui->actionDisplayToolBar->trigger();
    }
    if(Config.contains("window/lockToolBar") && Config.value("window/lockToolBar").toBool()){
        ui->actionLockToolBar->trigger();
    }

    if(Config.contains("window/toolButtonStyle")){
        QString style = Config.value("window/toolButtonStyle").toString();
        foreach(QAction *act, ui->menuToolBarStyle->actions()){
            if(act->objectName().endsWith(style)){
                act->setChecked(true);
                act->trigger();
                break;
            }
        }
    }

    QDir langdir("./lang/");
    foreach(QString lang, langdir.entryList(QStringList("*.qm"))){
        lang.remove(5, 3);
        QAction *action = ui->menuDisplayLanguage->addAction(lang);
        action->setCheckable(true);
        if(lang == Config.value("window/displayLanguage", "zh-CN").toString()){
            action->setChecked(true);
            ui->actionDefault->setChecked(false);
        }
    }
}

MainWindow::~MainWindow(){
    if(!isMaximized()){
        Config.setValue("window/Position", pos());
        Config.setValue("window/Size", size());
    }
    Config.setValue("window/State", (int) windowState());

    Config.setValue("window/hideToolBar", ui->mainToolBar->isHidden());
    Config.setValue("window/lockToolBar", !ui->mainToolBar->isMovable());

    foreach(QAction *act, ui->menuToolBarStyle->actions()){
        if(act->isChecked()){
            Config.setValue("window/toolButtonStyle", act->objectName().mid(6));
            break;
        }
    }

    foreach(QAction *act, ui->menuDisplayLanguage->actions()){
        if(act->isChecked()){
            Config.setValue("window/displayLanguage", act->text());
            break;
        }
    }
    if(ui->actionDefault->isChecked()){
        Config.remove("window/displayLanguage");
    }

    delete ui;
}

void MainWindow::startProcess(){
    const QMap<QString, QRect> *map = ui->graphicsView->getRectMap();

    if(map->isEmpty()){
        alertError(tr("You haven't draw any rects."));
    }else{
        progress_dialog->show();

        imgCutter->setRectMap(map);
        imgCutter->start();
    }
}

void MainWindow::alertError(QString message){
    QMessageBox::warning(this, tr("Warning!"), message);
}

void MainWindow::loadImage(const QString &image_path){
    ui->statusBar->showMessage(image_path);
    ui->graphicsView->setPixmap(image_path);
}

void MainWindow::on_actionOpen_triggered(){
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Input Directory"), Config.value("log/LastInputDirectory").toString());
    if(dir.isNull()){
        return;
    }

    if(imgCutter->setInputDirectory(dir)){
        ui->InputLineEdit->setText(dir);
        loadImage(dir + "/" + imgCutter->getImageSample());
        Config.setValue("log/LastInputDirectory", QVariant::fromValue(dir));
    }else{
        alertError(tr("We are sorry that the directory you selected contains no valid image files."));
    }
}

void MainWindow::on_actionSaveTemplate_triggered(){
    QString file_path = QFileDialog::getSaveFileName(this, tr("Save Template"), Config.value("log/LastTemplateDirectory").toString(), tr("JPG Tailor Template File(*.jtpl)"));
    if(file_path.isNull()){
        return;
    }

    ui->graphicsView->saveRectMap(file_path);
    QDir dir(file_path);
    dir.cdUp();
    Config.setValue("log/LastTemplateDirectory", QVariant::fromValue(dir.absolutePath()));
}

void MainWindow::on_actionLoadTemplate_triggered(){
    QString file_path = QFileDialog::getOpenFileName(this, tr("Open Template"), Config.value("log/LastTemplateDirectory").toString(), tr("JPG Tailor Template File(*.jtpl)"));
    if(file_path.isNull()){
        return;
    }

    ui->graphicsView->loadRectMap(file_path);
    QDir dir(file_path);
    dir.cdUp();
    Config.setValue("log/LastTemplateDirectory", QVariant::fromValue(dir.absolutePath()));
}

void MainWindow::on_actionOutputTo_triggered(){
    QString dir = QFileDialog::getExistingDirectory(this, tr("Select Output Directory"), Config.value("log/LastOutputDirectory").toString());
    if(dir.isNull()){
        return;
    }

    if(imgCutter->setOutputDirectory(dir)){
        ui->OutputLineEdit->setText(dir);
        Config.setValue("log/LastOutputDirectory", QVariant::fromValue(dir));
    }
}

void MainWindow::on_actionTerminatedTask_triggered(){
    QMessageBox::StandardButton button = QMessageBox::question(this,
        tr("Restore Terminated Task"),
        tr("Input Dir: ") + terminated_task.at(0) + "\n" + tr("Output Dir: ") + terminated_task.at(1),
        QMessageBox::Ok | QMessageBox::Cancel
    );

    if(button != QMessageBox::Ok){
        return;
    }

    if(imgCutter->setInputDirectory(terminated_task.at(0))){
        loadImage(terminated_task.at(0) + "/" + imgCutter->getImageSample());
    }else{
        alertError(tr("Image List Empty! The files in the previous input directory may be removed."));
        return;
    }

    if(!imgCutter->setOutputDirectory(terminated_task.at(1))){
        alertError(tr("JPG Tailor currently has no permission to write in the previous output directory(or it's been removed). Please modify the permission of it manually."));
        return;
    }

    ui->graphicsView->loadRectMap("./data/log_rectmap");

    imgCutter->setRectMap(ui->graphicsView->getRectMap());
    imgCutter->restart();
}

void MainWindow::on_actionLockToolBar_triggered(bool checked){
    ui->mainToolBar->setMovable(!checked);
}

void MainWindow::on_actionFullScreen_triggered(bool checked){
    if(checked){
        showFullScreen();
    }else{
        showNormal();
    }
}

void MainWindow::on_actionHelp_triggered(){
    QDesktopServices::openUrl(QUrl("help.pdf"));
}


void MainWindow::setToolButtonStyle(QAction *action){
    foreach(QAction *act, ui->menuToolBarStyle->actions()){
        act->setChecked(false);
    }

    action->setChecked(true);

    if(action->objectName().endsWith("TextOnly")){
        ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextOnly);
    }else if(action->objectName().endsWith("IconOnly")){
        ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
    }else if(action->objectName().endsWith("TextBesideIcon")){
        ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    }else{
        ui->mainToolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
    }
}

void MainWindow::setDisplayLanguage(QAction *action){
    foreach(QAction *act, ui->menuDisplayLanguage->actions()){
        act->setChecked(false);
    }
    action->setChecked(true);
}

void MainWindow::on_actionAboutUs_triggered(){
    QMessageBox::about(this, tr("About Us"), "Unicorz *\nTakashiro Satoshi, Cheng Cong\ntakashiro@qq.com");
}
